package com.water.camera.adapter;

import android.util.SparseArray;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.adapter.FragmentViewHolder;

import com.water.camera.fragment.ImgFragment;

import java.util.List;

public class BatchListAdapter extends FragmentStateAdapter {

    List<String> list;
    SparseArray<ImgFragment> array = new SparseArray<>();

    public BatchListAdapter(@NonNull FragmentActivity fragmentActivity, List<String> list) {
        super(fragmentActivity);
        this.list = list;
    }

    @NonNull
    @Override
    public Fragment createFragment(int position) {
        ImgFragment f = array.get(position, null);
        if (f == null) {
            f = new ImgFragment();
            array.put(position, f);
        }
        f.setPath(list.get(position));
        return f;
    }

    @Override
    public void onBindViewHolder(@NonNull FragmentViewHolder holder, int position,
                                 @NonNull List<Object> payloads) {
        super.onBindViewHolder(holder, position, payloads);
        if (!payloads.isEmpty()) {
            ImgFragment f = array.get(position, null);
            if (f != null) {
                f.setPath(payloads.get(0).toString());
            }
        }
    }

    @Override
    public int getItemCount() {
        return list == null ? 0 : list.size();
    }
}
